package cn.edu.zjgsu.ito.controller;

import cn.edu.zjgsu.ito.interceptor.AdminControllerInterceptor;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashSet;
import java.util.List;

import cn.edu.zjgsu.ito.model.TeacherInfo;
import cn.edu.zjgsu.ito.service.AdminTeaManageService;
import cn.edu.zjgsu.ito.service.CollegeCodeNameService;
import cn.edu.zjgsu.ito.service.ServiceFactory;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

@Before(AdminControllerInterceptor.class)
public class AdminTeaManageController extends Controller {

	AdminTeaManageService adminTeaManageService=ServiceFactory.createAdminTeaManageService();
	private CollegeCodeNameService collegeCodeNameService = ServiceFactory.createCollegeCodeNameService();
	private List<Record> Record1;
	/**
	 * 教师管理初始化
	 * 黄凯航
	 * 刘阳（改）
	 */
	public void index()
	{	
		List<Record> teacherInfos=Db.find("select * from teacher_info");
		List<Record> colleges=Db.find("select collegeCode from teacher_info");
		Record1=CollegeCodeNameService.allCollegeCodeName();	//获取所有学院名称和学院编号
		setAttr("allcollegeCodeName",Record1);
		HashSet<Record> c=new HashSet<Record>(colleges);
		colleges.clear();
		colleges.addAll(c);

		setAttr("college",colleges);
		setAttr("teacherInfo",teacherInfos);
		setAttr("collegeName",Db.find("select * from college"));
		render("teachermanage.html");	
	}
	/**
	 * 添加教师页面跳转
	 * 黄凯航
	 */
	public void add()
	{
		render("addteacher.html");
	}
	/**
	 * 添加教师
	 * 黄凯航
	 */
	public void submit()
	{
		TeacherInfo teacherInfo=getModel(TeacherInfo.class,"teacherInfo");
		String error=adminTeaManageService.addSingleTeacher(teacherInfo);
		setAttr("error",error);
		index();
	}
	/**
	 * 编辑教师页面跳转
	 * 黄凯航
	 */
	public void edit()
	{
		Integer id=getParaToInt(0);
		if(id!=null&&id>0)
			setAttr("teacherInfo",TeacherInfo.dao.findById(id));
		render("correctteacher.html");
	}
	/**
	 * 教师更新
	 * 黄凯航
	 */
	public void update()
	{
		TeacherInfo teacherInfo=getModel(TeacherInfo.class,"teacherInfo");
		String error=adminTeaManageService.updateSingleTeacher(teacherInfo);
		setAttr("error",error);
		index();
	}
	/**
	 * 异步教师更新
	 * 黄凯航
	 */
	public void ajaxupdate()
	{
		String tName=getPara("tName");
		String collegeCode=getPara("collegeCode");
		String title=getPara("title");
		int id=getParaToInt("id");
		String tNo=getPara("tNo");

		TeacherInfo teacherInfo = getModel(TeacherInfo.class);
		teacherInfo.set("tName", tName);
		teacherInfo.set("collegeCode", collegeCode);
		teacherInfo.set("title", title);
		teacherInfo.set("id", id);
		teacherInfo.set("tNo", tNo);

		String error=adminTeaManageService.updateSingleTeacher(teacherInfo);
		setAttr("error",error);
		setAttr("teacherInfo",TeacherInfo.dao.find("select * from teacher_info where id=?",id));
		System.out.println(error);
		System.out.println(teacherInfo);
		renderJson();
	}
	/**
	 * 教师搜索
	 * 黄凯航
	 */
	public void search()
	{
		String keyword=getPara("keyword").trim();
		List<Record> teacherInfos=Db.find("select * from teacher_info where tNo like ?","%"+keyword+"%");
		teacherInfos.addAll(Db.find("select * from teacher_info where tName like ?","%"+keyword+"%"));

		HashSet<Record> c=new HashSet<Record>(teacherInfos);
		teacherInfos.clear();
		teacherInfos.addAll(c);	

		setAttr("teacherInfo",teacherInfos);

		List<Record> colleges=Db.find("select college from teacher_info");
		c=new HashSet<Record>(colleges);
		colleges.clear();
		colleges.addAll(c);

		setAttr("college",colleges);
		render("teachermanage.html");
	}
	/**
	 * 异步教师搜索
	 * 黄凯航
	 */
	public void ajaxsearch()
	{try{
		String keyword=getPara("keyword");
		System.out.println("!"+keyword);
		List<TeacherInfo> teacherInfo=TeacherInfo.dao.find("select * from teacher_info where tNo like ?","%"+keyword+"%");
		teacherInfo.addAll(TeacherInfo.dao.find("select * from teacher_info where tName like ?","%"+keyword+"%"));

		HashSet<TeacherInfo> c=new HashSet<TeacherInfo>(teacherInfo);
		teacherInfo.clear();
		teacherInfo.addAll(c);

		System.out.println("!!"+teacherInfo);
		/*if(teacherInfo.size()==0)
		setAttr("error","找不到任何数据");*/
		renderJson(teacherInfo);
	}catch(Exception e){
		e.printStackTrace();
	}
	}
	/**
	 * 教师筛选
	 * 黄凯航
	 * 刘阳（改）
	 */
	public void screen()
	{		
		String keyword=getPara("keywords");
		String collegeCode = getPara("collegeCode");
		if(keyword.equals("all"))
			index();
		else
		{
			List<Record> teachers=Db.find("select * from teacher_info where collegeCode=?",collegeCode);
			setAttr("teacherInfo",teachers);

//			List<Record> colleges=Db.find("select college from teacher_info");
//			HashSet<Record> c=new HashSet<Record>(colleges);
//			colleges.clear();
//			colleges.addAll(c);

			setAttr("teachers",teachers);
			render("teachermanage.html");
		}
	}
	/**
	 * 教师异步筛选
	 * 黄凯航
	 * 刘阳（改）
	 */
	public void ajaxscreen()
	{		
		String keywords = getPara("keywords");

		if(keywords.equals("all"))
		{
			List<TeacherInfo> teacherInfo=TeacherInfo.dao.find("select * from teacher_info");
			renderJson(teacherInfo);
		}

		else
		{
			List<TeacherInfo> teacherInfo=TeacherInfo.dao.find("select * from teacher_info where collegeCode=?",keywords);
			renderJson(teacherInfo);
		}
	}
	/**
	 * 教师批量处理
	 * 黄凯航
	 */
	public void batch()
	{
		try{
			String action=getPara("action");
			int id=0;
			String tNo="";
			Record teacherTNo=new Record();
			//String[] teaCheckboxs=getParaValues("teaCheckbox");
			String checkboxValue=getPara("checkboxValue");
			String[] teaCheckboxs=checkboxValue.split(",");
			System.out.println("action="+action);
			for(int i=0;i<teaCheckboxs.length;i++)
				System.out.print(i+"="+teaCheckboxs[i]+"  ");
			//删除
			if(action.equals("delete")){
				for(int i=0;i<teaCheckboxs.length;i++) {
					id=Integer.parseInt(teaCheckboxs[i]);
					teacherTNo=Db.findById("teacher_info", id);
					tNo=teacherTNo.get("tNo");
					adminTeaManageService.deleteOrNot(tNo);
					teacherTNo=new Record();
				}
			}
			//重置密码
			if(action.equals("re")){
				for(int i=0;i<teaCheckboxs.length;i++) {
					id=Integer.parseInt(teaCheckboxs[i]);
					teacherTNo=Db.findById("teacher_info", id);
					tNo=teacherTNo.get("tNo");
					adminTeaManageService.rePassword(tNo);
					teacherTNo=new Record();
				}
			}
			redirect("/adminteamanage");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			redirect("/adminteamanage");
		}
	}
	/**
	 * 教师模板下载方法 
	 * 黄凯航
	 */
	public void fileDownload()
	{		
		String fileName="教师模板.xls";
		String path=JFinal.me().getConstants().getFileRenderPath();
		path=path+"/"+fileName;	
		renderFile(new File(path));		
	}
	/**
	 * 教师模板上传方法 
	 * 黄凯航
	 */
	public void fileUpload()
	{		
		String filedir=PathKit.getWebRootPath();
		filedir=filedir+"\\WEB-INF\\upload";
		try
		{
			UploadFile file=getFile("uploadFile");
			String fileName=file.getFileName();
			String extension=fileName.substring(fileName.lastIndexOf("."));
			if(extension.equals(".xls")||extension.equals(".XLS"))
			{
				File source=file.getFile();
				String newFileName=System.currentTimeMillis()+extension;
				FileInputStream fis=new FileInputStream(source);
				File targetDir=new File(filedir);
				File target=new File(targetDir,newFileName);
				FileOutputStream fos=new FileOutputStream(target);
				byte[] bts=new byte[300];
				while (fis.read(bts,0,300)!=-1){
					fos.write(bts,0,300);
				}
				fos.close();
				fis.close();
				source.delete();
				String error=adminTeaManageService.readTeacherTemplate(fileName, newFileName, filedir);
				setAttr("error",error);
				index();
			}
			else
			{
				setAttr("error","文件类型错误");
				index();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
